<template>
  <div class="app-container.home">
    <!-- 新增项目按钮 -->
    <el-button type="primary" @click="showAddFactoryDialog">新增项目</el-button>

    <!-- 新增项目的弹出框 -->
    <el-dialog
      title="新增项目"
      :visible.sync="addFactoryDialogVisible"
      width="30%"
    >
      <el-form ref="factoryForm" :model="factoryForm" label-width="80px">
        <el-form-item label="项目名称">
          <el-input v-model="factoryForm.factoryName" placeholder="请输入项目名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAddFactory">取消</el-button>
        <el-button type="primary" @click="confirmAddFactory">确定</el-button>
      </span>
    </el-dialog>


    <!-- 动态渲染工厂页面 -->
    <div v-for="(factory, index) in factories" :key="factory.name" class="factory-container">
      <h2>{{ factory.name }}</h2>
      <el-button type="danger" @click="showDelFactoryDialog(factory, index)">删除工厂</el-button>
      <!-- 在这里可以添加更多工厂相关的操作或内容 -->
    </div>
    <el-dialog
      title="删除项目"
      :visible.sync="delFactoryDialogVisible"
      width="30%"
    >
      <span>是否确认要删除{{currentFactory}}?</span>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="removeFactory(currentIndex)">确 定</el-button>
        <el-button @click="delFactoryDialogVisible = false;">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {addMenu, delMenu, listMenu} from '@/api/system/menu';
import pinyin from 'js-pinyin';
import axios from "axios";
import {getToken} from "@/utils/auth";

export default {
  name: 'Home',
  data() {
    return {
      // 控制弹出框的显示状态
      addFactoryDialogVisible: false,
      //删除弹窗
      delFactoryDialogVisible:false,
      currentFactory: null,   // 当前要删的工厂对象
      currentIndex: -1,        // 对应下标
      // 表单数据
      factoryForm: {
        factoryName: '' // 项目名称
      },
      // 存储项目信息
      factories: [],
      dataId:'',
      menuBrotherId:'',
      realPath:''
    };
  },
  created() {
    this.getDataId()
    this.loadFactory();
  },

  methods: {
    async getDataId() {
      const allMenus = await listMenu();
      const item = allMenus.data.find(m => m.menuType === 'M' &&  m.path === this.$route.params.item_project);
      this.dataId = item.menuId;
    },
    // 显示新增项目的弹出框
    showAddFactoryDialog() {
      this.addFactoryDialogVisible = true;
    },
    // 取消新增项目
    cancelAddFactory() {
      this.addFactoryDialogVisible = false;
      this.factoryForm.factoryName = ''; // 清空输入框
    },
    //删除弹窗
    showDelFactoryDialog(factory, index){
      this.delFactoryDialogVisible = true;
      this.currentFactory = factory.name;   // 当前要删的工厂对象
      this.currentIndex = index        // 对应下标
    },
    //获取项目下的项目名单
    loadFactory() {
      listMenu().then(res => {
        const nodes = res.data.filter(item => item.parentId === this.dataId);
        this.factories = nodes.filter(n => n.menuName !== '总览').map(n => ({ name: n.menuName }));
        if (!this.factories.length) console.warn('未找到项目下的数据');
      }).catch(err => {
        this.$modal.msgError('获取菜单失败：' + err.msg);
      });
    },
    //新增项目
    confirmAddFactory() {
      const factoryName = this.factoryForm.factoryName.trim();
      if (!factoryName) {
        this.$message.error('项目名称不能为空！');
        return;
      }
      if (this.factories.some(f => f.name === factoryName)) {
        this.$message.error('项目名称已存在！');
        return;
      }

      /* 1. 转拼音 */
      pinyin.setOptions({checkPolyphone: false, charCase: 0});
      const factoryNamePinyin = pinyin.getCamelChars(factoryName);

      /* 2. 组装菜单数据 */
      const pageData = {
        parentId: this.dataId,
        menuName: factoryName,
        icon: 'table',
        menuType: 'C',
        orderNum: 2,
        isFrame: '1',
        isCache: '0',
        visible: '0',
        status: '0',
        path: `${factoryNamePinyin}`,
        component: 'Factory/Base/template_index'
      }

      /* 3. 直接新增菜单 */
      addMenu(pageData).then(() => {
        axios.post('/dev-api/General/general/createTable',
          { project: factoryNamePinyin },
          { headers: {
              // 将 token 添加到请求头中，通常是 'Authorization' 头
              'Authorization': `Bearer ${getToken()}`
            }}).then(()=>{
          // 3-1. 本地 factories 列表也推一条
          this.factories.push({name: factoryName});
          // 3-2. 关闭弹窗 & 清空
          this.addFactoryDialogVisible = false;
          this.factoryForm.factoryName = '';
          // 3-3. 提示
          this.$modal.msgSuccess('项目与菜单均新增成功');
          // 当前页完整重载
          location.reload()
        })
      }).catch(err => {
        this.$modal.msgError('新增菜单失败：' + err.msg);});
    },
    // 删除项目
    removeFactory(index) {
      listMenu().then(res => {
        const item = res.data.find(m => m.menuType === 'C' && m.menuName.replace(/"/g, '') === this.factories[index].name);
        this.menuBrotherId = item.menuId;
        delMenu(this.menuBrotherId).then(()=>{
          pinyin.setOptions({checkPolyphone: false, charCase: 0});
          const factoryNamePinyin = pinyin.getCamelChars(this.factories[index].name);
          return axios.post('/dev-api/General/general/delTable',
            { project: factoryNamePinyin },
            { headers: {
                // 将 token 添加到请求头中，通常是 'Authorization' 头
                'Authorization': `Bearer ${getToken()}`
            }}
          )
        }).then(() => {
            this.factories.splice(index, 1);
            //当前页完整重载
            location.reload()
        }).catch(err => {this.$modal.msgError('删除失败' + err.msg);})
      })
      this.delFactoryDialogVisible = false;
    }
  }
};
</script>

<style scoped>
.factory-container {
  margin-top: 20px;
  border: 1px solid #ccc;
  padding: 10px;
  width: 100%;
  box-sizing: border-box;
}
</style>
